#include <iostream>
#include <string>
#include <unistd.h>
#include <pthread.h>

int tickets = 1000;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 全局的锁
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;    // 全局的条件变量

void *threadRoutine(void *args)
{
    std::string name = static_cast<const char *>(args);

    while (true)
    {
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            usleep(1000);
            std::cout << name << ", get a ticket: " << tickets-- << std::endl;
        }
        else
        {
            std::cout << "没有票了," << name << std::endl;
            pthread_cond_wait(&cond, &mutex); // 等待的时候，会把锁给释放掉
        }

        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

// 结果：先让三个线程互斥的抢1000张票，抢完了之后，等几秒钟，线程1，线程2，线程3依次等待抢票
int main()
{
    pthread_t tid1, tid2, tid3; // 创建三个线程

    pthread_create(&tid1, nullptr, threadRoutine, (void *)"thread-1");
    pthread_create(&tid2, nullptr, threadRoutine, (void *)"thread-2");
    pthread_create(&tid3, nullptr, threadRoutine, (void *)"thread-3");

    sleep(5);
    while (true)
    {
        sleep(6);
        pthread_mutex_lock(&mutex);
        tickets += 1000;
        pthread_mutex_unlock(&mutex);
        // pthread_cond_broadcast(&cond);
        pthread_cond_signal(&cond);
    }

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);

    return 0;
}
